#include "TextDoc.h"
#include "textContent.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

fstream inout;

TextDoc::TextDoc()
{
    //ctor
}


TextDoc::TextDoc(string Fn,bool ro, textContent *TC1)
{
	TC = TC1;
    filename = Fn;
    if(ro == 0)
    {
        load();
    }
    else
    {
        save();
    }
}

int TextDoc::load()
{
    inout.open(filename.c_str(), ios::in);

    //tjek if theres a file named that!
    if(inout.fail())
    {
        cout << "textdok: Theres no file named that" << endl;
        cout << "Exit Program" << endl;
        return 0;
    }
    //read data
	string buffer =".";
	string line; //to keep the line in
	string word; //for each word
    stringstream strstream;
    while(getline(inout,line)) //until EOF
	{

	    //cout << line.size() << "-";
//		cout << endl << line << endl;
        strstream.clear(); // to clear
		strstream.str(line);
		while(strstream >> word)
		{
		    TC->addWord(word);
            //cout << "(" << word << ")";
            /*if(word.substr(word.size()-1,word.size()) == ".") // || word.substr(word.size()-1,word.size()) == ","
            {
                TC->addWord(word.substr(0,word.size()-1));
                TC->addWord(word.substr(word.size()-1,word.size()));
//                cout << "-test-";
            }
            else
            {
                TC->addWord(word);
            }*/
		}
//		cout << "_ENT_";
		if(inout.eof())
		{
			break;
		}
		TC-> addWord("_ENT_");

	}
	inout.close();
	cout << "Done" << endl;
	return 0;
}

int TextDoc::save()
{
    //string str (".,!#%&/()=?");
    inout.open(filename.c_str(), ios::out);
	cout << endl;
	for(int i = 0; i < TC->getPosCound(); i++) //getPosCount = max numbers.
    {
		if (TC->getWordAtPos(i) == "_ENT_")
		{
			inout << '\n';
		}
		/*if(TC->getWordAtPos(i+1) == ".")
		{
		    inout << TC->getWordAtPos(i) << TC->getWordAtPos(i+1);
		}*/
		else
		{
            inout << TC->getWordAtPos(i);
            if(i+1 < TC->getPosCound() && TC->getWordAtPos(i+1) != "_ENT_") //to start after word 1 and to not put " " if \n is next,
            {
                inout << " ";
            }
		}
    }
    inout.close();
    cout <<"save" << endl;
    return 0;
}
